package handler

import (
	"context"
	"shop/shop-server/basic/config"
	"shop/shop-server/internal/model"
	__ "shop/shop-server/proto"
)

type ShopServer struct {
	__.UnimplementedShopServer
}

func (s *ShopServer) Add(_ context.Context, req *__.AddRequest) (*__.AddResponse, error) {
	shop := model.Shop{
		ProductNumber:  int32(req.ProductNumber),
		Classification: req.Classification,
		ProductImage:   req.ProductImage,
		ProductVideo:   req.ProductVideo,
		ProductName:    req.ProductName,
		InventoryUnit:  int8(req.InventoryUnit),
	}
	config.DB.Create(&shop)
	return &__.AddResponse{
		Id: int64(shop.Id),
	}, nil
}

func (s *ShopServer) Upload(_ context.Context, req *__.UploadRequest) (*__.UploadResponse, error) {
	return &__.UploadResponse{}, nil
}

func (s *ShopServer) AddS(_ context.Context, req *__.AddSRequest) (*__.AddSResponse, error) {
	spec := model.Specification{
		Colour:            req.Colour,
		SetMenu:           req.SetMenu,
		Image:             req.Image,
		SpecificationCode: req.SpecificationCode,
		RetailPrice:       float64(req.RetailPrice),
		CostPrice:         float64(req.CostPrice),
		WarningValue:      req.WarningValue,
		Inventory:         req.Inventory,
		Weight:            float64(req.Weight),
		SalesVolume:       req.SalesVolume,
	}

	config.DB.Create(&spec)
	return &__.AddSResponse{
		Id: int64(spec.Id),
	}, nil
}

func (s *ShopServer) AddOS(_ context.Context, req *__.AddOSRequest) (*__.AddOSResponse, error) {
	shop := model.Other_settings{
		AfterSales:      int8(req.AfterSales),
		ListingSettings: int8(req.ListingSettings),
		OpeningTime:     int8(req.OpeningTime),
	}
	config.DB.Create(&shop)
	return &__.AddOSResponse{
		Id: int64(shop.Id),
	}, nil
}
func (s *ShopServer) List(_ context.Context, req *__.ListShopRequest) (*__.ListShopResponse, error) {
	var shop []*model.Shop
	offset := (req.Page - 1) * req.PageSize
	config.DB.Offset(int(offset)).Limit(int(req.PageSize)).Find(&shop)
	var listShop []*__.ListShop
	for _, m := range shop {
		listShop = append(listShop, &__.ListShop{
			ProductDescription: m.ProductDescription,
			ProductNumber:      m.ProductNumber,
			Price:              float32(m.Price),
			Num:                m.Num,
			Classification:     m.Classification,
			State:              m.State,
		})
	}
	return &__.ListShopResponse{
		List: listShop,
	}, nil
}
